package com.cellulam.framework.scheduled;

import com.cellulam.framework.core.exceptions.SysException;
import com.cellulam.framework.scheduled.exceptions.TaskTerminateException;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 *
 */
@Slf4j
public class TaskProcessorHolder {

    public static final TaskProcessorHolder holder = new TaskProcessorHolder();

    private Map<String, TaskProcessor> processors = Maps.newHashMap();

    private TaskProcessorHolder() {

    }

    /**
     * 注册处理器
     *
     * @param processor
     */
    public void registerProcessor(TaskProcessor processor, Processor config) {
        int type = config.type();
        int version = config.version();

        if (config.taskType() != null) {
            type = config.taskType().getCode();
            version = config.taskType().getVersion();
        }

        if(type == 0) {
            throw new IllegalArgumentException("必须要配置任务类型");
        }

        String processorName = this.getProcessorName(type, config.command(), version);

        if (processors.containsKey(processorName)) {
            throw new SysException("存在重复处理器名称: " + processorName);
        }
        this.processors.put(processorName, processor);
        log.info("注册任务处理器{}成功", processorName);
    }

    /**
     * 获取处理器
     *
     * @return
     */
    public TaskProcessor getProcessor(int taskType, String cmd, int version) throws TaskTerminateException {

        String processorName = this.getProcessorName(taskType, cmd, version);

        TaskProcessor taskProcessor = this.processors.get(processorName);
        if (taskProcessor == null) {
            throw new TaskTerminateException("找不到处理器: " + processorName);
        }
        return taskProcessor;
    }


    private String getProcessorName(int taskType, String cmd, int version) {
        return String.format("%s$%s$v%s", taskType, cmd, version);
    }
}
